package {{packageName}}.server.router.impl.sys.handler

import com.firefly.annotation.Component
import com.firefly.annotation.InitialMethod
import com.firefly.annotation.Inject
import com.firefly.codec.http2.model.HttpHeader
import com.firefly.kotlin.ext.common.PathType
import com.firefly.kotlin.ext.http.AsyncHandler
import com.firefly.kotlin.ext.http.AsyncStaticFileHandler
import {{packageName}}.server.config.ServerConfig
import {{packageName}}.server.router.utils.recordAccessLog
import com.firefly.server.http2.router.RoutingContext
import com.firefly.utils.exception.CommonRuntimeException
import java.nio.file.Paths

/**
 * @author Pengtao Qiu
 */
@Component("staticResourceHandler")
class StaticResourceHandler : AsyncHandler {

    val staticResources = listOf("/favicon.ico", "/*.html", "/static/*")
    private val maxAge = 2 * 24 * 60 * 60
    private val maxBufferSize = 64 * 1024

    @Inject
    private lateinit var config: ServerConfig

    private lateinit var staticFileHandler: AsyncStaticFileHandler

    fun getStaticFileHandler() = staticFileHandler

    @InitialMethod
    fun init() {
        try {
            val type = PathType.parse(config.staticResourceRoot)
            staticFileHandler = when (type.type) {
                PathType.CLASS_PATH -> {
                    val path = Paths.get(StaticResourceHandler::class.java.getResource(type.path).toURI())
                    AsyncStaticFileHandler(path.toAbsolutePath().toString(), 64 * 1024, true)
                }
                PathType.FILE -> AsyncStaticFileHandler(type.path, maxBufferSize, false)
            }
        } catch (e: Exception) {
            throw CommonRuntimeException(e)
        }
    }

    override suspend fun handle(ctx: RoutingContext) {
        val startTime = System.currentTimeMillis()
        ctx.put(HttpHeader.CACHE_CONTROL, "max-age=$maxAge")
        staticFileHandler.handle(ctx)
        val endTime = System.currentTimeMillis()
        recordAccessLog(ctx, startTime, endTime)
    }

}